<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>django 4 django和postgresql | Jin Tian</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="Django" />
  
  
  
  
  <meta name="description" content="这个教程是要换数据库了，从mysql换到postgresql。说实话我个人以后决定使用postgresql，比mysql方便很多。">
<meta name="keywords" content="Django">
<meta property="og:type" content="article">
<meta property="og:title" content="Django 4 django和postgreSQL">
<meta property="og:url" content="http://yoursite.com/2017/01/26/Django-4-django和postgreSQL/index.html">
<meta property="og:site_name" content="Jin Tian">
<meta property="og:description" content="这个教程是要换数据库了，从mysql换到postgresql。说实话我个人以后决定使用postgresql，比mysql方便很多。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-02-02T13:23:06.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Django 4 django和postgreSQL">
<meta name="twitter:description" content="这个教程是要换数据库了，从mysql换到postgresql。说实话我个人以后决定使用postgresql，比mysql方便很多。">
  
    <link rel="alternate" href="/atom.xml" title="Jin Tian" type="application/atom+xml">
  

  

  <link rel="icon" href="/css/images/mylogo.jpg">
  <link rel="apple-touch-icon" href="/css/images/mylogo.jpg">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>
  <script src="/js/bootstrap.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >

  
    <link rel="stylesheet" href="/css/dialog.css">
  

  

  
    <link rel="stylesheet" href="/css/header-post.css" >
  

  
  
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>



  <body data-spy="scroll" data-target="#toc" data-offset="50">


  
  <div id="container">
    <div id="wrap">
      
        <header>

    <div id="allheader" class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-inner">
          
          <div class="container"> 
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>

            
              <a class="brand" style="
                 border-width: 0px;  margin-top: 0px;"  
                href="#" data-toggle="modal" data-target="#myModal" >
                  <img width="124px" height="124px" alt="Hike News" src="/css/images/mylogo.jpg">
              </a>
            
            
            <div class="navbar-collapse collapse">
              <ul class="hnav navbar-nav">
                
                  <li> <a class="main-nav-link" href="/">首页</a> </li>
                
                  <li> <a class="main-nav-link" href="/archives">归档</a> </li>
                
                  <li> <a class="main-nav-link" href="/categories">分类</a> </li>
                
                  <li> <a class="main-nav-link" href="/tags">标签</a> </li>
                
                  <li> <a class="main-nav-link" href="/about">关于</a> </li>
                
                  <li> <a class="main-nav-link" href="http://luoli-luoli.com/chat">chat</a> </li>
                
                  <li><div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(无标题)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div></li>
            </div>
          </div>
                
      </div>
    </div>

</header>



      
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Django-4-django和postgreSQL" style="width: 75%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Django 4 django和postgreSQL
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	<a href="/2017/01/26/Django-4-django和postgreSQL/" class="article-date">
	  <time datetime="2017-01-26T10:41:45.000Z" itemprop="datePublished">2017-01-26</time>
	</a>

      
      
	<a class="article-views">
	<span id="busuanzi_container_page_pv">
		阅读量<span id="busuanzi_value_page_pv"></span>
	</span>
	</a>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <p>这个教程是要换数据库了，从mysql换到postgresql。说实话我个人以后决定使用postgresql，比mysql方便很多。<br><a id="more"></a></p>
<blockquote>
<p>本文由作者金天原创，欢迎大家转载，不过请保留这段版权信息，多谢合作，如对本文有任何问题欢迎联系作者: jintianiloveu。</p>
</blockquote>
<h3 id="postgresql安装教程"><a href="#postgresql安装教程" class="headerlink" title="postgresql安装教程"></a>postgresql安装教程</h3><p>在这插入一下安装过程，之前安装了现在又重新搭建一遍所以记录一下，其实不管是Mac还是Linux都很简单，直接安装：<br><figure class="highlight mipsasm"><table><tr><td class="code"><pre><div class="line"><span class="comment"># mac</span></div><div class="line"><span class="keyword">brew </span><span class="keyword">install </span>postgresql</div><div class="line"></div><div class="line"><span class="comment"># ubuntu</span></div><div class="line">sudo apt <span class="keyword">install </span>postgresql</div></pre></td></tr></table></figure></p>
<p>当然除了安装数据库之外，还要安装我们需要的python适配器，从而在django中可以调用它，这里我们安装在virtualenv中把，但是之前一直没有用这个，现在也赶一下时髦用一下，其实大家如果不习惯用的话也没有关系，可以直接安装在系统的python目录下。<br><figure class="highlight cmake"><table><tr><td class="code"><pre><div class="line">pip3 <span class="keyword">install</span> psycopg2</div></pre></td></tr></table></figure></p>
<p>这个包是django用来和postgresql通信的python包，如果不安装的话会报错提醒你的。<br>注意在这里django默认使用了pillow来处理图片，因此在安装psycopg2的时候可以顺便把pillow安装一下，搞深度学习的应该都知道这个包，也就是python3下的pil。<br><figure class="highlight cmake"><table><tr><td class="code"><pre><div class="line">pip3 <span class="keyword">install</span> pillow</div></pre></td></tr></table></figure></p>
<h3 id="postgresql一分钟入门"><a href="#postgresql一分钟入门" class="headerlink" title="postgresql一分钟入门"></a>postgresql一分钟入门</h3><p>前几个教程一直是灌输mysql和django的知识，两个人其实配合的很好，今天突然来了第三者，大家可能会有点接受不了。容我解释一下，首先我觉得到目前为止转换的成本其实是很低的，你只需要卸载mysql，重新安装postgresql就可以了。所有的数据都还不多，无所谓。这里说明下我最终选择postgresql的原因：</p>
<ul>
<li>安装简单，没有复杂的密码，访问数据库和表简单</li>
<li>开源就不说了</li>
<li>和django搭配很友好，django其实官方是支持postgresql的</li>
</ul>
<p>最后还有一个很重要的原因就是：<strong>尼玛，sb mysql mac下每次重启系统就重置密码是鸡巴几个意思，shit，气得我直接抛弃了这个二笔</strong> 。</p>
<p>postgresql简单实用教程：<br><figure class="highlight vala"><table><tr><td class="code"><pre><div class="line"><span class="meta"># 创建一个用户</span></div><div class="line">sudo -u postgres createuser --superuser jfg</div><div class="line"><span class="meta"># 以postgres身份进入postgresql控制台</span></div><div class="line">sudo -u postgres psql</div><div class="line"><span class="meta"># 新建一个数据库</span></div><div class="line">sudo -u postgres createdb -O jfg oumenglite</div></pre></td></tr></table></figure></p>
<p>执行上面这些命令你可能觉得一头雾水，下面是postgresql的几条设计逻辑：</p>
<ul>
<li>postgresql是系统级的认证，就是你系统的用户名如果和postgresql用户名相同，则postgresql就不会进行第二步验证</li>
<li>postgresql实行的是每个数据库不同管理员制，也就是说你可以为每个数据库单独设置管理员</li>
</ul>
<p>好了了解了上面两条逻辑，下面运行和几个命令，首先我们创建一个和当前系统用户名相同的postgresql用户，创建完之后你的系统用户就是postgresql的超级用户，不用指定用户也不用输入密码，方便快捷：<br><figure class="highlight ada"><table><tr><td class="code"><pre><div class="line">sudo -U postgres createuser <span class="comment">--superuser yoursysusername</span></div></pre></td></tr></table></figure></p>
<p>这样你就可以直接输入<code>psql</code>来操作数据库了。</p>
<p><strong>[UPDATE 2017-02-1]</strong></p>
<p>更官方的的postgresql使用应该是这样的，你安装完之后会有一个默认的用户postgres，然后：<br><figure class="highlight ada"><table><tr><td class="code"><pre><div class="line">sudo su postgres</div><div class="line">createuser <span class="comment">--interactive -P</span></div></pre></td></tr></table></figure></p>
<p>这是会提示你创建一个新的用户，然后：<br><figure class="highlight ada"><table><tr><td class="code"><pre><div class="line">createdb <span class="comment">--owner yourjusttypename databasename</span></div></pre></td></tr></table></figure></p>
<h3 id="django和postgresql之歌"><a href="#django和postgresql之歌" class="headerlink" title="django和postgresql之歌"></a>django和postgresql之歌</h3><p>现在django之歌要改成django和postgresql之歌了。我们所有的数据都将基于postgresql来构建，我们插入几条数据来看看显示效果：<br><figure class="highlight gherkin"><table><tr><td class="code"><pre><div class="line">from users_user;</div><div class="line">  1 |<span class="string"> 金天 </span>|<span class="string"> 男     </span>|<span class="string"> 1993-12-11 </span>|<span class="string">              </span>|<span class="string">      </span>|<span class="string">             </span>|<span class="string"> lewisjin@outlook.com </span>|<span class="string">        </span>|<span class="string">         </span>|<span class="string"> 长沙        </span>|</div><div class="line">  2 |<span class="string"> 小芳 </span>|<span class="string"> 女     </span>|<span class="string"> 1993-12-11 </span>|<span class="string">              </span>|<span class="string">      </span>|<span class="string">             </span>|<span class="string"> xiaof@qq.com         </span>|<span class="string">        </span>|<span class="string">         </span>|<span class="string"> 北京        </span>|</div><div class="line">  3 |<span class="string"> 刘明 </span>|<span class="string"> 男     </span>|<span class="string"> 1993-12-11 </span>|<span class="string">              </span>|<span class="string"> 浙江  </span>|<span class="string"> 15116378920 </span>|<span class="string"> xiaof@qq.com         </span>|<span class="string">        </span>|<span class="string">         </span>|<span class="string"> 北京        </span>|</div></pre></td></tr></table></figure></p>
<p>感觉数据多的情况下，postgresql的控制台显示效果都比mysql的好，而且你上手postgresql只需要知道这么几条命令就够了：<br><figure class="highlight vala"><table><tr><td class="code"><pre><div class="line"><span class="meta"># 新建数据库</span></div><div class="line">createdb ara</div><div class="line"></div><div class="line"><span class="meta"># 选择数据库</span></div><div class="line">psql ara</div><div class="line"></div><div class="line"><span class="meta"># 显示所有数据库</span></div><div class="line">psql -l</div><div class="line"></div><div class="line"><span class="meta"># 显示数据库下的所有表</span></div><div class="line">\d</div></pre></td></tr></table></figure></p>
<p>就是这么simple。你已经从mysql转移到了postgresql！</p>
<h3 id="django继续我们的api"><a href="#django继续我们的api" class="headerlink" title="django继续我们的api"></a>django继续我们的api</h3><p>时隔很久了，这个教程只要继续我们的django代建restful api的伟大事业。</p>

      
    </div>
    <footer class="article-footer">
      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '骚年，加个好友打赏一下啊，现在连泡面都吃不起了啊', // 可选参数，打赏标题
  btnText: '打赏支持', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://i.loli.net/2017/09/27/59cb048ba6838.jpeg',
  alipayImage: 'https://i.loli.net/2017/09/27/59cb049cd0951.jpeg'
});
</script>
      
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8zMDA5MC82NjQ1">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>



      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Django/">Django</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/02/01/2017-1-6-OpenCV-Clion-C++-开发环境搭建教程/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          Ubuntu下用Clion和C++开发OpenCV程序教程
        
      </div>
    </a>
  
  
    <a href="/2017/01/16/Django-3-分分钟搭建一个RESTful-API/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">Django 3 分分钟搭建一个RESTful API</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="toc-sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    
        <ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#postgresql安装教程"><span class="nav-number">1.</span> <span class="nav-text">postgresql安装教程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#postgresql一分钟入门"><span class="nav-number">2.</span> <span class="nav-text">postgresql一分钟入门</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#django和postgresql之歌"><span class="nav-number">3.</span> <span class="nav-text">django和postgresql之歌</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#django继续我们的api"><span class="nav-number">4.</span> <span class="nav-text">django继续我们的api</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      
      <footer id="footer">
  

  <div class="container">
      	<div class="row">
	      <p> Powered by <a href="http://www.luoli-luoli.com/" target="_blank">萝莉萝莉</a> and <a href="http://www.luoli-luoli.com/sia" target="_blank">Sia</a> </p>
	      <p id="copyRightEn">Copyright &copy; 2017 - 2018 Jin Tian All Rights Reserved.</p>
	      
	      
    		<p class="busuanzi_uv">
				访客数 : <span id="busuanzi_value_site_uv"></span> |  
				访问量 : <span id="busuanzi_value_site_pv"></span>
		    </p>
  		   
		</div>

		
  </div>
</footer>


<!-- min height -->

<script>
    var wrapdiv = document.getElementById("wrap");
    var contentdiv = document.getElementById("content");
    var allheader = document.getElementById("allheader");

    wrapdiv.style.minHeight = document.body.offsetHeight + "px";
    if (allheader != null) {
      contentdiv.style.minHeight = document.body.offsetHeight - allheader.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    } else {
      contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    }
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
    <a href="http://luoli-luoli.com/chat" class="mobile-nav-link">Chat</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>




  <script src="/js/dialog.js"></script>








	<div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2 class="modal-title" id="myModalLabel">设置</h2>
      </div>
      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">


      <div class="modal-body">
          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" onclick="javascript:setFontSize();" aria-expanded="true" aria-controls="collapseOne">
              正文字号大小
            </a>
          </div>
          <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            您已调整页面字体大小
          </div>
        </div>
      


          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" onclick="javascript:setBackground();" aria-expanded="true" aria-controls="collapseTwo">
              夜间护眼模式
            </a>
        </div>
          <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
          <div class="panel-body">
            夜间模式已经开启，再次单击按钮即可关闭 
          </div>
        </div>

        <div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关 于&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
        </div>
         <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
          <div class="panel-body">
            Jin Tian
          </div>
          <div class="panel-body">
            Copyright © 2018 Jintian All Rights Reserved.
          </div>
        </div>
      </div>


      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
    </div>
  </div>
</div>
  
  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
  
    <a id="menu-switch"><i class="fa fa-bars fa-lg"></i></a>
  
</body>
</html>